package cn.org.xiaosheng.core.registery;

import cn.org.xiaosheng.core.loadBalance.LoadBalancer;
import cn.org.xiaosheng.core.loadBalance.RoundRobinRule;
import cn.org.xiaosheng.core.utils.NacosUtils;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * 服务发现接口
 * @author XiaoSheng
 * @date 2024/8/22 上午10:42
 */
public class NacosServerDiscovery implements ServerDiscovery {

    private final LoadBalancer loadBalancer;

    public NacosServerDiscovery(LoadBalancer loadBalancer) {
        this.loadBalancer = loadBalancer == null ? new RoundRobinRule() : loadBalancer;
    }


    @Override
    public InetSocketAddress getService(String serviceName) throws NacosException {
        List<Instance> allInstance = NacosUtils.getAllInstance(serviceName);
        if (allInstance == null || allInstance.size() == 0) {
            throw new RuntimeException(serviceName + "找不到服务!");
        }
        Instance instance = loadBalancer.getInstance(allInstance);
        return new InetSocketAddress(instance.getIp(), instance.getPort());
    }
}
